<template>
	<view>
		<Navbar :showLeft="false" title="在线考试"></Navbar>
		<view class="exam">
			<uni-section title="考试模式选择" type="line" v-if="status != 'loading'">
				<uni-data-picker placeholder="请选择模式" popup-title="考试模式设置" :localdata="dataTree" v-model="classes"
					@change="onchange" @nodeclick="onnodeclick" @popupopened="onpopupopened"
					>
				</uni-data-picker>
			</uni-section>
			<uni-section title="历史考试记录" type="line" v-if="status != 'loading' && !classes ">
				<uni-collapse accordion v-model="value" ref="collapse" @change="change">
					<uni-collapse-item v-for="(item, index) in historyExam"  :title="item.time">
						<uni-list  style="margin-left: 15px;">
							<uni-list-item v-for="(subItem, index) in item.children" :note="subItem.status == 1 ? '已完成' : '未完成'"
								:title="`${subItem.startTime}~${subItem.endTime}`">
								<template v-slot:footer>
									<button type="primary" size="mini" style="width: auto;height: 30px;"
										@click="showHistoryExam(subItem)">查看</button>
									<button type="warn" size="mini" style="width: auto;height: 30px;margin-left: 10px;"
										@click="delHistoryExam(subItem.examId)">删除</button>
								</template>
							</uni-list-item>
						</uni-list>
					</uni-collapse-item>
				</uni-collapse>
			</uni-section>
			<uni-section v-if="ok && status != 'loading' && classes" class="test-model" title="自定义配置" type="line">
				<view>
					<text>组卷模式：</text>
					<uni-data-checkbox style="padding-bottom: 0px;" v-model="formData.radio1"
						:localdata="simpleChoice1"></uni-data-checkbox>
				</view>
				<view style="margin-top: 10px;" v-if="!classes.startsWith('1-1')">
					<text>试题类型：</text>
					<uni-data-checkbox :multiple="true" style="padding-bottom: 0px;" v-model="formData.radio2"
						:localdata="simpleChoice2"></uni-data-checkbox>
				</view>
				<view style="margin-top: 10px;" v-if="classes.startsWith('1-2')">
					<text>试题分类：</text>
					<uni-data-checkbox :multiple="true" style="margin-top: 10px;" v-model="formData.multi1"
						:localdata="simpleChoice3"></uni-data-checkbox>
				</view>
				<view style="margin-top: 10px;" v-if="!classes.startsWith('1')">
					<text>试题分类：</text>
					<uni-data-checkbox :multiple="true" style="padding-bottom: 0px;margin-top: 10px;"
						v-model="formData.multi1" :localdata="categoryList"></uni-data-checkbox>
				</view>
				<view style="margin-top: 10px;" v-if="!classes.startsWith('1')">
					<text>试题数量：</text>
					<uni-row style="margin-top: 10px;">
						<uni-col span="12" v-if="check(0)">
							<view class="demo">
								<text>单选：</text>
								<uni-number-box :min="5" :max="40" :value="formData.count1" @change="h1" />
							</view>
						</uni-col>
						<uni-col span="12" v-if="check(2)">
							<view class="demo">
								<text>多选：</text>
								<uni-number-box :min="0" :max="10" :value="formData.count2" @change="h2" />
							</view>
						</uni-col>

					</uni-row>
					<uni-row style="margin-top: 10px;">
						<uni-col style="margin-bottom: 10px;" span="12" v-if="check(1)">
							<view class="demo">
								<text>判断：</text>
								<uni-number-box :min="0" :max="20" :value="formData.count3" @change="h3" />
							</view>
						</uni-col>
						<uni-col style="margin-bottom: 10px;" span="12" v-if="check(3)">
							<view class="demo">
								<text>综合：</text>
								<uni-number-box :min="0" :max="7" :value="formData.count4" @change="h4" />
							</view>
						</uni-col>
					</uni-row>
				</view>
				<view v-if="!classes.startsWith('1-1')" style="margin-top: 10px;">
					<text>考试时间(分)：</text>
					<uni-number-box style="margin-top: 10px;" :min="1" :max="180" :value="formData.radio3"
						:step="formData.radio3 >= 10 ? 5 : 1" @change="h5" />
				</view>
				
				<view>
					<button
						style="background: linear-gradient(to right, #9060df, #6356de);width: 120px;margin-top: 20px;border-radius: 15px;"
						type="primary" size="default" @click="createExam">
						确定
					</button>
				</view>
			</uni-section>
			<uni-load-more :content-text="contentText" v-show="status=='loading'" iconType="circle" color="#007AFF"
				:status="status" />
		</view>

		<!--获取用户未完成的考试-->
		<!-- <ExamNoFinishedModel></ExamNoFinishedModel> -->
	</view>
</template>

<script setup>
	import {
		onLoad,
		onShow
	} from "@dcloudio/uni-app";
	import {
		ref,
		reactive,
		getCurrentInstance,
		nextTick,
		watch
	} from "vue";
	import ExamNoFinishedModel from "./ExamNoFinishedModel.vue";
	import {
		LOCAL_STORAGE_KEY
	} from "@/utils/Constants.js";
	import {
		Radio
	} from "@dcloudio/uni-h5";
	const {
		proxy
	} = getCurrentInstance();

	import {
		usePageOpStore
	} from "@/stores/pageOp";
	const pageOpStore = usePageOpStore();
	const modalRef = ref({})
	const ok = ref(false)
	const value = ref("1")
	const formData = ref({
		radio1: 0,
		radio2: [0],
		radio3: 60,
		count1: 5,
		count2: 0,
		count3: 0,
		count4: 0,
		multi1: []
	})
	const userToken = {};
	const simpleChoice1 = [{
		text: '默认',
		value: 0
	}, {
		text: '打乱',
		value: 1
	}]
	const simpleChoice2 = [{
		text: '判断题',
		value: 0
	}, {
		text: '单选题',
		value: 1
	}, {
		text: '多选题',
		value: 2
	}, {
		text: '综合题',
		value: 3
	}]
	const simpleChoice3 = ref([])
	const categoryList = ref([]);
	const classes = ref("")
	const dataTree = ref([])
	const historyExam = ref([])
	const status = ref("")
	const contentText = {
		contentdown: '查看更多',
		contentrefresh: '正在进行后台组卷',
		contentnomore: '系统出现异常'
	}
	onShow(() => {
		
		const token = uni.getStorageSync(LOCAL_STORAGE_KEY.token.key);
		console.log(token)
		// 判断用户是否登录
		if (token == "" || token == null) {
			uni.navigateTo({
				url: "/pages/account/LoginAndRegister",
			});
			return;
		}
		loadHistoryExam()
		pageOpStore.setOp(false, true);
	});
	const loadHistoryExam = async () => {
		let result = await proxy.Request({
			url: proxy.Api.loadHistoryExam
		});
		if (!result) return
		historyExam.value = result.data
	}
	const showHistoryExam = async (item) => {
		let result = await proxy.Request({
			url: proxy.Api.loadHistoryExamById,
			params: {
				id: item.examId
			}
		});
		if (!result.data) {
			return;
		}
		result.data.examInfo.status = item.status
		result.data.examInfo.score = item.score
		uni.setStorageSync("examQuestionList", result.data.examQuestionList)
		uni.setStorageSync("examInfo", result.data.examInfo)
		status.value = "noMore"
		uni.navigateTo({
			url: "./ExamQuestion?examId=" + result.data.examInfo.examId 
		});
	}
	const delHistoryExam = async (id) => {
		uni.showModal({
			title: '提示',
			content: '你确定要删除吗',
			success: async function(res) {
				if (res.confirm) {
					let result = await proxy.Request({
						url: proxy.Api.delExam,
						params: {
							examId: id
						}
					});
					loadHistoryExam()
				} else if (res.cancel) {
					console.log('取消');
				}
			}
		})
	}
	const check = (id) => {
		const arr = formData.value.radio2
		for (let i = 0; i < arr.length; i++) {
			if (arr[i] == id) return true
		}
		return false
	}
	const h1 = (value) => {
		formData.value.count1 = value
	}
	const h2 = (value) => {
		formData.value.count2 = value
	}
	const h3 = (value) => {
		formData.value.count3 = value
	}
	const h4 = (value) => {
		formData.value.count4 = value
	}
	const h5 = (value) => {
		formData.value.radio3 = value
	}
	const onpopupopened = async () => {
		let result = await proxy.Request({
			url: proxy.Api.loadModels
		});
		if (!result) return
		dataTree.value = result.data
	}
	const loadAllCategoryList = async () => {
		let result = await proxy.Request({
			url: proxy.Api.loadAllCategory,
			showLoading: false,
		});
		if (!result) {
			return;
		}
		for (let i = 0; i < result.data.length; i++) {
			let check = result.data[i].text == "计算机组成原理" ||
				result.data[i].text == "数据结构" ||
				result.data[i].text == "操作系统" ||
				result.data[i].text == "计算机网络"
			if (check) simpleChoice3.value.push(result.data[i])
		}
		categoryList.value = result.data;

	};
	const onchange = (e) => {
		if (categoryList.value.length == 0) {
			loadAllCategoryList()
		}
		// formData.value.multi1 = []
		// formData.value.count1 = 5
		// formData.value.count2 = 0
		// formData.value.count3 = 0
		// formData.value.count4 = 0
		// formData.value.radio1 = 0
		// formData.value.radio3 = 60
		// formData.value.radio2 = [0]
		ok.value = true
	}
	const getExamModel = () => {
		if (classes.value.startsWith("1-1")) {
			return 0
		} else if (classes.value.startsWith("1-2")) {
			return 1
		}
		return 2;
	}
	const createExam = async () => {
		status.value = "loading"
		const token = uni.getStorageSync(LOCAL_STORAGE_KEY.token.key);
		// 判断用户是否登录
		if (token == "" || token == null) {
			status.value = ""
			uni.navigateTo({
				url: "/pages/account/LoginAndRegister",
			});
			return;
		}
		const examModel = getExamModel()
		if (examModel == 0) formData.value.radio3 = 60
		formData.value.examModel = examModel
		formData.value.id = search(dataTree.value).contentId
		let result = await proxy.Request({
			url: proxy.Api.createExam,
			params: formData.value,
			dataType: 'json'
		});
		if (!result) {
			return;
		}
		uni.setStorageSync("examQuestionList", result.data.examQuestionList)
		uni.setStorageSync("examInfo", result.data.examInfo)
		status.value = "noMore"
		uni.navigateTo({
			url: "./ExamQuestion?examId=" + result.data.examInfo.examId 
		});
	};
	const search = (list) => {
		for (let i = 0; i < list.length; i++) {
			if (list[i].value == classes.value) {
				return list[i]
			}
			if (classes.value.startsWith(list[i].value) && list[i].children) {
				let res = search(list[i].children);
				return res;
			}
		}
	}
</script>

<style lang="scss" scoped>
	.footer-button {
		display: flex;

	}

	.demo {
		display: flex;
		align-items: center;
	}

	j .test-model {
		flex-direction: column;
		display: flex;
		align-items: flex-start;
		// overflow: hidden;
	}

	.exam {
		padding: 10px;

		.category-title {
			font-weight: bolder;
			padding: 10px 5px;
		}

		.btn-panel {
			margin-top: 10px;

			uni-button[type="primary"] {
				background: #6e80e5;
			}
		}

		.select-all {
			margin-top: 20px;
		}

		.tips {
			font-size: 14px;
			margin-top: 10px;
			color: #7f7f7f;
		}
	}
</style>